package cn.dakaqi.apps.group.admin.controller;

import cn.dakaqi.apps.group.admin.shiro.ShiroDbRealm;
import cn.dakaqi.entities.*;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.services.*;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.utils.CodeMap;
import cn.dakaqi.utils.DKQConstant;
import cn.dakaqi.utils.Dictionary;
import cn.dakaqi.utils.redis.RedisClientTemplate;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chunyang on 2016/5/12.
 */
public abstract class BaseController
{
    public static final String PAGE_SIZE = "1";

    @Autowired
    GroupMonthDataService groupMonthDataService;
    @Autowired
    GroupRecruitVolunteerService groupRecruitVolunteerService;
    @Autowired
    VolunteerService volunteerService;
    @Autowired
    GroupVolunteerService groupVolunteerService;
    @Autowired
    GroupService groupService;
    @Autowired
    RedisClientTemplate redisClientTemplate;
    @Autowired
    GroupRecruitService groupRecruitService;


    //当前用户
    public Volunteer volunteer = null;
    //当前社团
    public Group group = null;
    //当前用户加入的所有社团
    public List<Group> groups = null;
    //服务领域
    public List<Dictionary> userServiceFiled = null;
    //专业技能
    public List<Dictionary> userSkill = null;
    //职业
    public List<Dictionary> userJob = null;
    //网站菜单数据、左路个人数据
    public ModelMap modelMap = null;
    //本社团待审核成员数量
    public int groupWaiteApplys = 0;
    //本社团招募待审核数量
    public int groupRecriuteWaiteApplys = 0;

    public ModelAndView modelAndView = null;
    String key = "";

    public ModelMap initData(String groupCode, HttpServletRequest request)
    {

        modelMap = new ModelMap();
        this.group = null;
        //当前用户信息
        volunteer = this.volunteerService.findByUserId(getCurrentUserId());
        System.out.println("getCurrentUserId-->" + getCurrentUserId());
        groups = new ArrayList<Group>();
        if (null == groupCode || "null".equals(groupCode) || StringUtils.isBlank(groupCode))
        {
            System.out.println("group-----1---------->" + group);
            //当用户可以管理的所有组织
            List<GroupVolunteer> groupVolunteerList = groupVolunteerService.findByAdmin(volunteer.getMemberCode());

            if (null != groupVolunteerList && groupVolunteerList.size() > 0)
            {
                for (GroupVolunteer gv : groupVolunteerList)
                    groups.add(gv.getGroup());

                group = groups.get(groupVolunteerList.size() - 1);
            }

            System.out.println("group-----12---------->" + group);

        }
        else
        {
            System.out.println("group-----2---------->" + group);
            group = this.groupService.findByGroupCode(groupCode);
            //当用户可以管理的所有组织
            List<GroupVolunteer> groupVolunteerList = groupVolunteerService.findByAdmin(volunteer.getMemberCode());

            if (null != groupVolunteerList && groupVolunteerList.size() > 0)
            {
                for (GroupVolunteer gv : groupVolunteerList)
                    groups.add(gv.getGroup());
            }

            System.out.println("group-----22---------->" + group);
        }
        //查询当前社团中待审核的人员数量

        //查询当前待挂靠的社团数据

        //服务领域
        userServiceFiled = CodeMap.getUserServiceFiled();
        //专业技能
        userSkill = CodeMap.getUserSkill();
        //职业
        userJob = CodeMap.getJob();

        modelMap.addAttribute("userServiceFiled", userServiceFiled);
        //专业技能
        modelMap.addAttribute("userSkill", userSkill);
        //职业
        modelMap.addAttribute("userJob", userJob);
        //证件类型
        modelMap.addAttribute("cardType", CodeMap.getCardType());

        modelMap.addAttribute("volunteer", volunteer);

        if(null != groups)
            modelMap.addAttribute("groups", groups);

        if (null != group)
        {
            modelMap.addAttribute("group", group);
            request.getSession().setAttribute("curGroup", group);
            setGroupApplys(group.getGroupCode());
        }
        if (null != volunteer)
            request.getSession().setAttribute("volunteer", volunteer);

        if (null != group)
        {
            //准备图表数据
            charData(group.getGroupCode(), modelMap);
            //查询本社团加入待审核人数 招募待审核人数
            setGroupApplys(group.getGroupCode());

            key = "initData_" + group.getGroupCode();
            redisClientTemplate.set(key, JSON.toJSONString(modelMap));
        }

        return modelMap;
    }

    private void setGroupApplys(String groupCode)
    {
        groupRecriuteWaiteApplys = 0;
        //查询本社团待审核的成员数量
        groupWaiteApplys = this.groupVolunteerService.counts(this.groupService.findByGroupCode(groupCode).getId(), DKQConstant.APPLY_STATUS);
        modelMap.addAttribute("groupWaiteApplys", groupWaiteApplys);
        //查询本社团招募待审核人数量
        GroupRecruit groupRecruit = groupRecruitService.findLastByGroupCode(groupCode, DKQConstant.PROCEED_START);
        if (null != groupRecruit)
        {
            List<GroupRecruitVolunteer> list = this.groupRecruitVolunteerService.findVerfierByGroupRecruit(groupRecruit.getId(), DKQConstant.APPLY_STATUS);
            if (null != list)
                groupRecriuteWaiteApplys = list.size();
        }
        modelMap.addAttribute("groupRecriuteWaiteApplys", groupRecriuteWaiteApplys);
    }


    private void charData(String groupCode, ModelMap modelMap)
    {
        //categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        StringBuffer categories = new StringBuffer();
        //data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
        StringBuffer volunters = new StringBuffer();
        StringBuffer activities = new StringBuffer();
        StringBuffer times = new StringBuffer();
        //
        Page<GroupMonthData> data = this.groupMonthDataService.findByGroupCode(groupCode);
        if (null != data && data.getContent() != null && data.getContent().size() > 0)
        {

            for (GroupMonthData gmd : data.getContent())
            {
                String month = gmd.getMonth();
                categories.append("'");
                categories.append(month);
                categories.append("'");
                categories.append(",");


                int _volunteers = gmd.getVolunteers();
                volunters.append(_volunteers);
                volunters.append(",");


                int _activites = gmd.getActivities();
                activities.append(_activites);
                activities.append(",");


                int _times = gmd.getTimes();
                times.append(_times);
                times.append(",");

            }

            modelMap.addAttribute("categories", categories.toString().substring(0, categories.toString().length() - 1));
            modelMap.addAttribute("volunters", volunters.toString().substring(0, volunters.toString().length() - 1));
            modelMap.addAttribute("activities", activities.toString().substring(0, activities.toString().length() - 1));
            modelMap.addAttribute("times", times.toString().substring(0, times.toString().length() - 1));

        }
    }

    public void clearInitData()
    {
        redisClientTemplate.del(key);
    }

    protected abstract ModelAndView initModelAndView(String groupCode, String view, HttpServletRequest request);

    protected abstract void clearModelAndView(String groupCode, HttpServletRequest request);

    /**
     * 取出Shiro中的当前用户Id.
     */
    private Long getCurrentUserId()
    {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        return user.id;
    }

    /**
     * 更新Shiro中当前用户的用户名.
     */
    private void updateCurrentUserName(String userName)
    {
        ShiroDbRealm.ShiroUser user = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
        user.realName = userName;
    }
}
